package com.huawei.esdk.tpoa.business.oa.sitemgr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.huawei.esdk.platform.authorize.itf.IAuthorize;
import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.ThreadLocalHolder;
import com.huawei.esdk.platform.common.bean.aa.AccountInfo;
import com.huawei.esdk.platform.common.config.ConfigManager;
import com.huawei.esdk.platform.common.constants.ESDKConstant;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.common.utils.ApplicationContextUtil;
import com.huawei.esdk.platform.common.utils.StringUtils;
import com.huawei.esdk.platform.nemgr.itf.IDeviceManager;
import com.huawei.esdk.tp.authorize.SessionManager;
import com.huawei.esdk.tp.common.constants.InfoKeys;
import com.huawei.esdk.tp.common.constants.TPConstant;
import com.huawei.esdk.tp.domain.model.Site;
import com.huawei.esdk.tp.domain.model.bean.PagedList;
import com.huawei.esdk.tp.domain.model.bean.QuerySites;
import com.huawei.esdk.tp.domain.model.bean.SortField;
import com.huawei.esdk.tpoa.business.oa.mapping.TPOADataMapping;

public class TPOASiteManager extends Thread
{
    public final static Map<String, Site> tpSites = new HashMap<String, Site>();
    
    //    public final static Map<String, Site> exchangeSites = new HashMap<String, Site>();
    
    private String EMAILDOMAIN;
    
    private static final Logger LOGGER = Logger.getLogger(TPOASiteManager.class);
    
    private IAuthorize authorize;
    
    private ExecutorService es = Executors.newCachedThreadPool();
    
    public void init()
    {
        this.start();
    }
    
    @Override
    public void run()
    {
        ThreadLocalHolder.get().getEntities().put(ESDKConstant.CURRENT_PRODUCT, "tpoa.office365");
//        authorize.setAuthPolicy("tpoa", ESDKConstant.AUTH_POLICY_SINGLE_ACCT);
        
        AccountInfo esdkAcct = new AccountInfo();
        ThreadLocalHolder.get().getEntities().put(ESDKConstant.ACCT_INFO_ESDK, esdkAcct);
        ThreadLocalHolder.get().getEntities().put(InfoKeys.SDK_SESSION_ID.toString(), "");
        
        SessionManager sessionMgr = SessionManager.getInstance();
        sessionMgr.saveSDKSession(TPConstant.SMC_LOGIN_CLIENT_TYPE_OA);
        
        try
        {
            
            String exchangeDevId = TPConstant.DEV_ID_EXCHANGE;
            IDeviceManager deviceManager = ApplicationContextUtil.getBean("deviceManager");
            List<Map<String, Object>> deviceInfo = deviceManager.queryDeviceInfo(exchangeDevId);
            if(null != deviceInfo && 0 < deviceInfo.size())
            {
                String exchangeDeviceName = (String)deviceInfo.get(0).get("username");
                int indexChar = exchangeDeviceName.indexOf("@");
                if(-1 != indexChar)
                {
                    EMAILDOMAIN = exchangeDeviceName.substring(indexChar);
                }
            }
              
            if(null == EMAILDOMAIN)
            {
                LOGGER.error("Exchange deive not found, synch site free busy will failed!");
                return;
            }

            //获取所有TP会场
            loadAllTPSites();
            
//            //获取所有Exchange room resource
//            loadAllExchangeSites();
            
            //为TP会场和Exchange room resource 创建映射关系
            createTPOASiteMapping();
            
            //启动会场同步线程
            TPOASiteSynchronization siteSynchronization = new TPOASiteSynchronization();
            siteSynchronization.init();
            
            es.execute(siteSynchronization);
        }
        catch (SDKException e)
        {
            LOGGER.error("loadAllTPSites method error", e);
        }
        catch (Exception e)
        {
            LOGGER.error("loadAllExchangeSites method error", e);
        }
    }
    
    public void destroy()
    {
        es.shutdownNow();
    }
    
    public void loadAllTPSites()
        throws SDKException
    {
        QuerySites querySites = new QuerySites();
        int currentPage = 1;
        querySites.setCurrentPage(currentPage);
        
        int numberPerPage = 50;
        String numberPerPageStr = ConfigManager.getInstance().getValue("tpoa_queryAllSites_numberPerPage");
        if (!StringUtils.isEmpty(numberPerPageStr))
        {
            try
            {
                numberPerPage = Integer.parseInt(numberPerPageStr);
            }
            catch (NumberFormatException e)
            {
                LOGGER.error("NumberFormatException for numberPerPageStr,set default value 50", e);
                numberPerPage = 50;
            }
        }
        
        querySites.setNumberPerPage(numberPerPage);
        List<SortField> sortFields = new ArrayList<SortField>();
        querySites.setSortField(sortFields);
        
        SDKResult<PagedList<Site>> sites = null;
        
        boolean flag = true;
        
        while (flag)
        {
            try
            {
                sites = Site.querySites(querySites);
            }
            catch (Exception e)
            {
                try
                {
                    Thread.sleep(30 * 1000);
                    continue;
                }
                catch (InterruptedException e1)
                {
                    LOGGER.error(e1);
                }
            }
            
            if (null != sites && 0 == sites.getErrCode())
            {
                PagedList<Site> sitePagedList = sites.getResult();
                for (Site site : sitePagedList.getRecords())
                {
                    tpSites.put(site.getUri(), site);
                }
                int curPageNo = sitePagedList.getCurPageNo();
                int totalPageCount = sitePagedList.getTotalPageCount();
                if (curPageNo < totalPageCount)
                {
                    querySites.setCurrentPage(curPageNo + 1);
                }
                else
                {
                    flag = false;
                }
            }
            else
            {
                flag = false;
            }
        }
        
    }
    
    
    public void createTPOASiteMapping()
    {
        
        
        if (null == tpSites)
        {
            return;
        }
        
        for (Entry<String, Site> tpSite : tpSites.entrySet())
        {
            String tpSiteUri = tpSite.getValue().getUri();
            String mailAddress = tpSiteUri + EMAILDOMAIN;
            TPOADataMapping.siteUriMapping.put(mailAddress, tpSiteUri);
        }
    }
    
    
    public IAuthorize getAuthorize()
    {
        return authorize;
    }
    
    public void setAuthorize(IAuthorize authorize)
    {
        this.authorize = authorize;
    }
}
